#!/usr/bin/python
# -*- coding: utf-8 -*-
# AUTHOR:   guangling.hou@gmail.com
# FILENAME: py_http.py
# CREATED:  13:34:22 10/12/2012
# MODIFIED: 2014-04-11 09:58

import urllib3
from  py_decode import PY_Decode
import time
import gevent
from gevent.pool import Pool
import random
from dm_py_util import *
from gevent import monkey
"""
连接池的py_http模块
"""
class PYC_HttpClient():

	#初始化一个http连接
	def __init__(self):
		self._httppools = {}
		self._decoder = PY_Decode()
		self._response = ''
		#一次最多允许10个并发

	"""
	参数：
		Method: POST or GET
		Timeout: 超时时间
		Body: Post的内容
		Headers: 自定义header
		Uri: urlencode后的请求Uri(unicode编码)
	返回：
		返回的响应(一般是unicode编码,除非解析不出编码或者是二进制内容)
	"""
	def request(self,Uri,Method = 'GET',Timeout = 1,Body = None,Headers = None):
		self._response = ''	
		return self._request_with_pool_map(
				Uri = Uri,
				Method = Method,
				Timeout = Timeout,
				Body = Body,
				Headers = Headers,
				HttpPoolMap = self._httppools)

	def get_uri_info(self,uri):
		if not uri:
			return (None,None)
		uri_info = urllib3.util.parse_url(uri)
		if uri_info.scheme != 'http':
			return (None,None)
		return (uri_info.host,uri_info.port)


	def _request_with_pool_map(self,Uri,Method,Timeout,Body,Headers,HttpPoolMap):
		if not isinstance(Uri,unicode):
			raise DM_InputError('must input unicode')	

		uri_info = self.get_uri_info(Uri)
		if not uri_info[0]:
			raise DM_InputError('Uri error %s' % Uri)

		pool = None
		if HttpPoolMap.has_key(uri_info):
			pool = HttpPoolMap[uri_info]
		else:
			print 'get pool'
			pool = urllib3.connectionpool.HTTPConnectionPool(host = uri_info[0],
							port = uri_info[1],
							maxsize = 10,
							block = False)
			HttpPoolMap[uri_info] = pool
			print 'finish pool'

		return self._request_with_pool(Uri = Uri,
								  Method = Method,
								  Timeout = Timeout,
								  Body = Body,
								  Headers = Headers,
								  HttpPool = pool)


	def _request_with_pool(self,Uri,
			Method = 'GET',
			Timeout = 1,
			Body = None,
			Headers = None, 
			HttpPool = None):
		if not HttpPool:
			raise DM_InnerError('HttpPool is None')

		t = Timeout/2.0
		n_timeout = urllib3.util.Timeout(connect = t,read = t,total = Timeout)

		print n_timeout

		try:
			if Method == 'GET':
				print Uri
				print 'get Url'
				response = HttpPool.request(method = Method,
						url = Uri.encode('utf-8'),
						fields=None,
						timeout = n_timeout,
						headers = Headers,
						retries = False)
				print response.data,type(response.data)
			elif Method == 'POST':
				if Body:
					if not isinstance(Body,unicode):
						raise DM_InputError('must input unicode')

				response = HttpPool.urlopen(method = Method,
						url = Uri,
						body = Body.encode('utf-8'),
						timeout = n_timeout, 
						headers = Headers,
						retries = False)
			else:
				raise DM_InputError('Only support GET and POST')

		except Exception,e:
			raise DM_HttpRequestError(str(e))
	
		self._response = self._decoder.decode(response.data) 
		return self._response



class PYC_MultiHttpClient():

	def __init__(self):
		self._gevent_pool = Pool(10)
		self._decoder = PY_Decode()
		self._mhttpclients = []

	def multi_get(self,Uris = [],Timeout = 1,Headers = None):
		monkey.patch_socket()
		try:
			map(isinstance,Uris,[unicode for uri in Uris])
		except Exception,e:
			raise DM_InputError(str(e))	
		
		if len(self._mhttpclients) < len(Uris):
			for i in xrange(len(Uris) - len(self._mhttpclients)):
				httpclient = PYC_HttpClient()
				self._mhttpclients.append(httpclient)
		
		rs = [self._gevent_pool.spawn(self._mhttpclients[i].request,
						Uri = Uris[i],
						Method = 'GET',
						Timeout = Timeout,
						Body = None,
						Headers = Headers) for i in xrange(len(Uris))]
		gevent.joinall(rs)
		return [self._mhttpclients[i]._response for i in xrange(len(Uris))]
		

def pool_request(i,Method):
	print i%10
	gevent.sleep(2)
	print i%10,Method,'finish'




if __name__ == '__main__':
	
	#单个请求
	httpclient = PYC_HttpClient()
	#uri = "http://server97.beta1.duomi.com:5345/user/set_user?uid=649734&nick=你好啦"
	#uri = "http://192.168.2.107:7035/sdj/room/info?room_id=2"
	#uri = "http://192.168.2.107:7035/sdj/room/active?room_id=2"
	#uri = "http://sdjapi.duomi.com/api-gettrack?id=1157308"
	#uri = "http://192.168.2.107:7035/sdj/room/active?room_id=2"
	#uri = "http://localhost:3333/"
	uri = "http://userinfo.sns.duomi.com/user/queryuser?format=json&uid=11955856"
	uri = uri.decode('utf-8')
	res = httpclient.request(Uri = uri,
					Timeout = 1)

	print res,type(res)
	exit(0)


	##多个GET请求
	#u1 = "http://192.168.2.107:7035/sdj/room/info?room_id=2"
	#u2 = "http://192.168.2.107:7035/sdj/room/info?room_id=3"
	#uris = []
	#uris.append(u1.decode('utf-8'))
	##uris.append(u1)
	#uris.append(u2.decode('utf-8'))
	#print uris

	#mhttpclient = PYC_MultiHttpClient()
	#print mhttpclient.multi_get(uris)

	##pool = Pool(10) 

	##rs = [pool.spawn(pool_request,i,Method = 'zdsf') for i in range(0,100)]
	##gevent.joinall(rs)

	

